package com.lotusfall.config;

import com.lotusfall.service.UserService;
import com.lotusfall.pojo.Permission;
import com.lotusfall.pojo.Role;
import com.lotusfall.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import com.lotusfall.service.PermissionService;
import com.lotusfall.service.RoleService;

import java.util.HashSet;
import java.util.List;
import java.util.Set;


@Component
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserService userService;

    @Autowired
    private RoleService roleService;

    @Autowired
    private PermissionService permissionService;

    // 从数据库查询用户
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userService.selectUserByUsername(username);
        System.out.println(username);

        if(user != null){
            // 不为空，说明该用户，处理角色
            System.out.println(user.getPassword());
            Set authorities = new HashSet<>();
            List<Role> roles = roleService.listRoleByUserid(user.getId());
            for (Role role : roles) {
                authorities.add(new SimpleGrantedAuthority("ROLE_" + role.getName()));
            }
            List<Permission> permissions = permissionService.listPermissionByUserid(user.getId());
            for (Permission permission : permissions) {
                if (permission == null) {
                    authorities.add(new SimpleGrantedAuthority(permission.getName()));
                }

            }
            return new UserSecurity(user,authorities);
        }
        return null;
    }
}
